﻿using System;
using System.Text;
using Models = Evaluant.Uss.Models;
using Evaluant.Uss.DomainModel.OptionModel;
using Evaluant.Uss.SqlMapper;

namespace MappingGenerator
{
    public class TablePerConcreteClass : IMappingImpl
    {
        public TablePerConcreteClass(Models.Model model, Option option)
            : base(model, option)
        {
        }

        public override Mapping CreateMapping()
        {
            Models.EntityCollection baseEntities = _model.GetBaseEntities();

            Mapping mapping = new Mapping();
            foreach (Models.Entity entity in baseEntities)
            {
                EntityOption parentEntityOption = GetEntityOption(entity.Type);

                string parentTable = parentEntityOption.TableName;

                EntityMapping parentEntityMapping = BuildEntityMapping(entity, parentEntityOption);
                mapping.Entities.Add(parentEntityMapping);

                foreach (Models.Entity child in _model.GetTree(entity.Type))
                {
                    if (child == entity)
                        continue;

                    EntityOption childEntityOption = GetEntityOption(child.Type);

                    EntityMapping childEntityMapping = BuildEntityMapping(child, childEntityOption);

                    childEntityMapping.CopyNode = parentEntityMapping.Type;

                    mapping.Entities.Add(childEntityMapping);
                }
            }

            foreach (Models.Reference relation in _model.GetAllReferences())
            {
                EntityMapping parent = mapping.Entities[relation.ParentType, true];
                AttributeMapping am = new AttributeMapping();
                am.Name = relation.Name;

                am.DbType = System.Data.DbType.AnsiString;

                am.ParentEntity = parent;
                parent.Attributes.Add(am);
                continue;


                foreach (Models.Entity pe in _model.GetTree(relation.ParentType))
                {
                    EntityMapping parentEntityMapping = mapping.Entities[pe.Type, true];

                    foreach (Models.Entity child in _model.GetTree(relation.ChildType))
                    {
                        AttributeMapping amm = new AttributeMapping();
                        amm.Name = relation.Name;

                        amm.DbType = System.Data.DbType.AnsiString;

                        amm.ParentEntity = parentEntityMapping;
                        parentEntityMapping.Attributes.Add(amm);
                    }
                }
            }

            return mapping;
        }

    }
}
